import { getUserInfo } from "@/apis/userInfo"
import router from '@/router'
const state = {
  // 用户信息
  userInfo: localStorage.getItem("userInfo") || null,
  // 用户token
  token: localStorage.getItem("token") || null,
  // 是否已登录
  isLoggedIn: localStorage.getItem("isLoggedIn") || false,
  isLoggedDialogVisible: false,
}

const mutations = {
  // 设置用户信息
  SET_USER_INFO(state, userInfo) {
    state.userInfo = JSON.stringify(userInfo)
    // 同步到localStorage
    if (userInfo) {
      localStorage.setItem("userInfo", JSON.stringify(userInfo))
    } else {
      localStorage.removeItem("userInfo")
    }
  },

  // 设置token
  SET_TOKEN(state, token) {
    state.token = token
    if (token) {
      localStorage.setItem("token", token)
    } else {
      localStorage.removeItem("token")
    }
  },

  // 设置登录状态
  SET_LOGIN_STATUS(state, status) {
    state.isLoggedIn = status
    // 同步到localStorage
    if (status) {
      localStorage.setItem("isLoggedIn", "true")
    } else {
      localStorage.removeItem("isLoggedIn")
    }
  },

  // 清除用户信息
  CLEAR_USER_INFO(state) {
    state.userInfo = null
    state.token = null
    state.isLoggedIn = false
    // 清除localStorage
    localStorage.removeItem("userInfo")
    localStorage.removeItem("token")
    localStorage.removeItem("isLoggedIn")
  },
  SET_LOGIN_DIALOG_VISIBLE(state, status) {
    state.isLoggedDialogVisible = status
  },
}

const actions = {
  // 获取用户信息
  async fetchUserInfo({ commit, state ,  }) {
    try {
      if (!state.isLoggedIn) {
        return
      }
      const response = await getUserInfo()
      commit("SET_USER_INFO", response.data)
        return response.data
    } catch (error) {
      console.error("刷新用户信息失败:", error)
      throw error
    }
  },

  // 登录
  async login({ commit, dispatch,rootState }, { token, userInfo }) {
    commit("SET_TOKEN", token)
    if (userInfo) {
      commit("SET_USER_INFO", userInfo)
    }
    commit("SET_LOGIN_STATUS", true)
    userInfo = await dispatch("fetchUserInfo")
    commit("SET_USER_INFO", userInfo)
    const route = rootState.route
    if(route.name !== 'home') {
      window.history.replaceState(null, null, window.location.origin + '/#/home')
    router.replace('/home')
    }
    return userInfo
  },

  // 更新用户信息
  updateUserInfo({ commit }, userInfo) {
    commit("SET_USER_INFO", userInfo)
  },
}

const getters = {
  // 获取用户信息
  userInfo: (state) => {
    const userInfo = state.userInfo || localStorage.getItem("userInfo")
    // console.log('getters---userInfo :>> ', JSON.parse(userInfo));

    return JSON.parse(userInfo) || {}
  },

  // 获取token
  token: (state) => state.token || localStorage.getItem("token"),

  // 是否已登录
  isLoggedIn: (state) => state.isLoggedIn || localStorage.getItem("isLoggedIn"),

  // 是否显示登录弹框
  isLoggedDialogVisible: (state) => state.isLoggedDialogVisible,
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}
